<script setup lang="ts">
import { ref, unref } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { ElTree, ElButton, ElLoading, ElMessageBox } from 'element-plus'
import {
  adminCsClassAddApi,
  adminCsClassEditApi,
  adminCsClassListApi,
  adminCsClassDelApi
} from '@/api/cs/class'
// import { TableData } from '@/api/CsClass/types'
import { useI18n } from '@/hooks/web/useI18n'
import { Dialog } from '@/components/Dialog'
import Edit from './components/Edit.vue'

const { t } = useI18n()
// const loading = ref(false)
const loading = ref({
  tree: false,
  save: false
})
const iconSize = 16
const iconColor = '#999'

const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const formData = ref<any>({})

const listData = ref<any>([])
const defaultProps = {
  children: 'children',
  label: 'class_name'
}

const deleteApi = async (class_id) => {
  const res = await adminCsClassDelApi({ class_id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    getList()
  }
}

const action = (type: string, data: any) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = t('编辑菜单')
      formData.value = data
      if (formData.value.disp_order != null && typeof formData.value.disp_order === 'string') {
        formData.value.disp_order = Number(formData.value.disp_order)
      }
      dialogVisible.value = true
      break
    case 'addChildren':
      dialogTitle.value = t('新增下级菜单')
      formData.value = {
        parent_id: data.class_id,
        disp_order: 0
      }
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = t('新增菜单')
      formData.value = {
        parent_id: '0',
        disp_order: 0
      }
      dialogVisible.value = true
      break
    case 'delete':
      ElMessageBox.confirm('确定要删除这个菜单？', '删除菜单', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteApi(data.class_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const getList = async () => {
  // const loadingInstance = ElLoading.service(options)
  const loadingMain = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await adminCsClassListApi({})
    .catch(() => {})
    .finally(() => {
      setTimeout(() => {
        loadingMain.close()
      }, 500)
    })
  if (res) {
    listData.value = res.data
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const save = async (type: string) => {
  const edit = unref(editRef)
  await edit?.elFormRef?.validate(async (isValid) => {
    // console.log('isValid', isValid)
    if (isValid) {
      // 点击后先让按钮loading
      loading.value.save = true
      const newData: any = await edit?.getFormData()
      const data = { ...edit.oldFormData, ...newData }
      switch (type) {
        case 'edit':
          const res = await adminCsClassEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value.save = false
            })
          if (res) {
            dialogVisible.value = false
            getList()
          }
          break
        case 'addChildren':
        case 'add':
          const addRes = await adminCsClassAddApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value.save = false
            })
          if (addRes) {
            dialogVisible.value = false
            getList()
          }
          break
        default:
          console.log('未知类型')
      }
    }
  })
}

//初始化
getList()
</script>

<template>
  <ContentWrap>
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add', {})">新增</ElButton>
    </div>

    <div class="custom-tree-container">
      <el-tree
        :data="listData"
        :props="defaultProps"
        node-key="class_id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node }">
          <span class="custom-tree-node">
            <!-- <span>{{ t(node.data.menu_name) }}</span> -->
            <span>{{ t(node.label) }}</span>
            <span>
              <a @click="action('edit', node.data)">
                <Icon
                  icon="el:edit"
                  title="编辑"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('addChildren', node.data)">
                <Icon
                  icon="carbon:add-filled"
                  title="创建下级"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('delete', node.data)">
                <Icon
                  icon="fluent:delete-20-filled"
                  title="删除"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
            </span>
          </span>
        </template>
      </el-tree>
    </div>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit ref="editRef" :formData="formData" :meunData="listData" />
    <template #footer>
      <ElButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="loading.save"
        @click="save(actionType)"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;

  a {
    padding: 0 3px;

    i {
      margin-top: 5px;
    }
  }
}
</style>
